package net.qqxh.common.utils;

import java.io.*;
import java.util.Properties;


/**
 * @author jsaon
 */
public class PropertiesTool {


    /**
     * 修改或添加键值对 如果key存在，修改, 反之，添加。
     *
     * @param file  文件路径
     * @param key   键
     * @param value 键对应的值
     */
    public static void writeData(File file, String key, String value) {

        Properties prop = new Properties();
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            InputStream fis = new FileInputStream(file);
            prop.load(fis);
            //一定要在修改值之前关闭fis
            fis.close();
            OutputStream fos = new FileOutputStream(file);
            prop.setProperty(key, value);
            //保存，并加入注释
            prop.store(fos, "Update '" + key + "' value");
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)  {
        String libofficeHome = getLibofficeHome();
        System.out.println(libofficeHome);
        writeData(getPropFile(), "jodconverter.officeHome", libofficeHome);
    }

    public static File getPropFile() {
        String path = new PropertiesTool().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String prop = new File(path).getParent() + File.separator + "config" + File.separator + "application-prod.properties";
        return new File(prop);
    }

    public static String getLibofficeHome() {
        String path = new PropertiesTool().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String jfsSettingPath = new File(path).getParent() + File.separator + "LibreOffice";
        return jfsSettingPath;
    }
}